<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
 * This is a sample module for PyroCMS
 *
 * @author 		Jerel Unruh - PyroCMS Dev Team
 * @website		http://unruhdesigns.com
 * @package 	PyroCMS
 * @subpackage 	Sample Module
 */
class Admin extends Admin_Controller
{
	protected $section = 'user_namager';
	protected $_ci;
	public function __construct()
	{
		parent::__construct();

		// Load all the required classes
		$this->load->library('form_validation');
		$this->_ci = &get_instance();
		$this->load->model('uploking_files_m');
		$this->load->model('uploking_folders_m');
		$this->load->model('uploking_users_m');
		$this->load->helper('uploking');
		$this->lang->load('uploking_admin');
		
		// Set the validation rules
		$this->validation_rules = array(
			array(
				'field' => 'first_name',
				'label' => 'lang:uploking_admin_user_manager_first_name_label',
				'rules' => 'trim|required'
			),
			array(
				'field'	=> 'last_name',
				'label'	=> 'lang:uploking_admin_user_manager_last_name_label',
				'rules' => 'trim|required'
			),
			array(
				'field'	=> 'password',
				'label'	=> 'lang:uploking_admin_user_manager_password_label',
				'rules' => 'trim|max_length[255]|min_length[6]|matches[retype_password]'
			),
			array(
				'field'	=> 'retype_password',
				'label'	=> 'lang:uploking_admin_user_manager_retype_password_guide_label',
				'rules' => 'trim|max_length[255]'
			),
			array(
				'field' => 'active',
				'label' => 'lang:uploking_admin_user_manager_status_label'
			)
		);
		
		$this->template->set_partial('shortcuts', 'admin/partials/shortcuts')
						->append_metadata(js('escort.banner.js', 'banner'))
						->append_metadata(css('escort.banner.css', 'banner'));
	}

	/**
	 * List all items
	 */
	public function index()
	{
		//set the base/default where clause
		$base_where = array();
	
		$base_where = $this->input->post('f_site') ? $base_where + array('site' => $this->input->post('f_site')) : $base_where;

		// Create pagination links
		$total_rows = $this->uploking_users_m->count_by($base_where);
		$pagination = create_pagination('admin/user_manager/index', $total_rows);

		// Using this data, get the relevant results
		$userList = $this->uploking_users_m->limit($pagination['limit'])->get_many_by($base_where);

		//do we need to unset the layout because the request is ajax?
		$this->input->is_ajax_request() ? $this->template->set_layout(FALSE) : '';

		$this->template
			->title($this->module_details['name'])
			->append_metadata(js('admin/filter.js'))
			->set('pagination', $pagination)
			->set('userList', $userList);

		$this->input->is_ajax_request() ? $this->template->build('admin/tables/posts', $this->data) : $this->template->build('admin/index', $this->data);
			
	}
	
	public function create()
	{
		$this->form_validation->set_rules($this->validation_rules);
		$ci = &get_instance();
		
		$this->data->bannerCountryList = null;
		if ($this->form_validation->run())
		{
			$site_ids = '';
			$siteIdsArray = $this->input->post('site_ids');
			
			foreach ($siteIdsArray as $key => $value) {
				$site_ids .= $value.',';
			}
			$site_ids = substr($site_ids,0, strlen($site_ids) - 1);
			
			$define_text = "";
			$image = "";
			$alt_image = "";
			$script = "";
			if($this->input->post('banner_type') == "text"){
				$define_text = $this->input->post('define_text'); 
			}
			
			if($this->input->post('banner_type') == "script"){
				$script = $this->input->post('script');
			}
			
			if($this->input->post('banner_type') == "image"){
				$config['upload_path'] = './uploads/default/files/banners';
				$config['allowed_types'] = 'gif|jpg|png';
				$config['max_size']	= '10000';
				$config['max_width']  = '1024';
				$config['max_height']  = '768';
				
				$this->load->library('upload', $config);
				
				if ($this->upload->do_upload('image'))
				{
					$imageData = $this->upload->data();
					$image = $imageData['file_name'];
					$alt_image =  $this->input->post('title');
				}else{
					die("upload file error");
					$image = "";
				}
			}
			
			$id = $this->escort_ads_banners_m->insert(array(
						 'user_added' => $ci->ion_auth->get_user()->username,
						 'permission_slug' => $ci->ion_auth->get_user()->group,
						  'site_ids' => $site_ids,
						  'ads_zone_id' =>  $this->input->post('ads_zone_id'),
						  'banner_type' => $this->input->post('banner_type'),
						  'define_text' => $define_text  ,
						  'title' 		=> $this->input->post('title'),
						  'follow'    => $this->input->post('follow'),
						  'image' => $image  ,
						  'alt_image' => $alt_image,
						  'link' =>  $this->input->post('link') ,
						  'script'  => $script,
						  'display_after_login' => $this->input->post('display_after_login'),
						  'updated_time'  =>time() ,
						  'active'  => $this->input->post('active')
					));
			
			$countryList = $this->input->post('country_id');
			$regionList = $this->input->post('state_id');
			$provinceList = $this->input->post('province_id');
			$this->escort_ads_banner_display_geolocations_m->delete_by('ads_banner_id', $id);
			foreach($countryList as $key => $value){
				if($countryList[$key]){
					$country_id = $countryList[$key];
				}else{
					$country_id = 0;
				}
				if($regionList[$key]){
					$region_id = $regionList[$key];
				}else{
					$region_id = 0;
				}
				if($provinceList[$key]){
					$province_id = $provinceList[$key];
				}else{
					$province_id = 0;
				}
				
				$this->escort_ads_banner_display_geolocations_m->insert(array(
								'ads_banner_id'	=> $id,
								'country_id'	=> $country_id,
								'region_id'	=> $region_id,
								'province_id'	=> $province_id
				));
			}
			
			if ($id)
			{
				do_log(LOG_ACTION_BACKEND, 0, $this->_ci->ion_auth->get_user()->username, 'escort_log_add_banner', array($id));
				$this->session->set_flashdata('success', sprintf($this->lang->line('blog_post_add_success'), $this->input->post('title')));
			}
			else
			{
				$this->session->set_flashdata('error', $this->lang->line('blog_post_add_error'));
			}
			$this->input->post('btnAction') == 'save_exit' ? redirect('admin/banner') : redirect('admin/banner/edit/' . $id);
		}
		else
		{
			// Go through all the known fields and get the post values
			foreach ($this->validation_rules as $key => $field)
			{
				$banner->$field['field'] = set_value($field['field']);
			}

			if(($banner->banner_type == null) || ($banner->banner_type == '')){
				$banner->banner_type = "text";
			}

			$banner->user_added = $ci->ion_auth->get_user()->username;
		}

		$this->template
			->title($this->module_details['name'], lang('escort_banner_create_title'))
			->append_metadata($this->load->view('fragments/wysiwyg', $this->data, TRUE))
			->append_metadata(js('jquery/jquery.tagsinput.min.js'))
			->append_metadata(js('blog_form.js', 'blog'))
			->append_metadata(css('jquery/jquery.tagsinput.css'))
			->set('banner', $banner)
			->build('admin/form', $this->data);
	}
	public function edit($id = 0)
	{
		$id OR redirect('admin/user_manager');
	
		$user = $this->uploking_users_m->get($id);
	
		$this->form_validation->set_rules($this->validation_rules);
		
		if ($this->form_validation->run())
		{
			$password = $this->input->post('password');
			if($password){
				$password = md5($password);
			}else{
				$password = $user->password;
			}
			$result = $this->uploking_users_m->update($id, array(
					  'first_name' => $this->input->post('first_name'),
					  'last_name' =>  $this->input->post('last_name'),
					  'password' => $password,
					  'active'  => $this->input->post('active')
			));

			if ($result)
			{
				$this->session->set_flashdata(array('success' => sprintf(lang('uploking_admin_user_manager_update_success_label'), $user->username)));
			}
				
			else
			{
				$this->session->set_flashdata('error', $this->lang->line('uploking_admin_user_manager_update_error_label'));
			}
	
			// Redirect back to the form or main page
			$this->input->post('btnAction') == 'save_exit' ? redirect('admin/user_manager') : redirect('admin/user_manager/edit/' . $id);
		}
	
		// Go through all the known fields and get the post values
		foreach ($this->validation_rules as $key => $field)
		{
			if (isset($_POST[$field['field']]))
			{
				$user->$field['field'] = set_value($field['field']);
			}
		}
		
		$this->template
		->title($this->module_details['name'], sprintf(lang('uploking_admin_user_manager_edit_user_label'), $user->username))
		->append_metadata($this->load->view('fragments/wysiwyg', $this->data, TRUE))
		->set('user', $user)
		->build('admin/form', $this->data);
	}
	public function delete($id = 0)
	{
		// Delete one
		$ids = ($id) ? array($id) : $this->input->post('action_to');
	
		// Go through the array of slugs to delete
		if ( ! empty($ids))
		{
			$banner_titles = array();
			foreach ($ids as $id)
			{
				// Get the current page so we can grab the id too
				if ($user = $this->uploking_users_m->get($id))
				{
					$this->uploking_users_m->delete($id);
					$this->pyrocache->delete('uploking_users_m');
					$user_usernames[] = $user->username;
				}
			}
		}
	
		// Some pages have been deleted
		if ( ! empty($user_usernames))
		{
			// Only deleting one page
			if (count($user_usernames) == 1)
			{
				$this->session->set_flashdata('success', sprintf($this->lang->line('uploking_admin_user_manager_delete_success_label'), $user_usernames[0]));
			}
			// Deleting multiple pages
			else
			{
				$this->session->set_flashdata('success', sprintf($this->lang->line('uploking_admin_user_manager_mass_delete_success_label'), implode('", "', $user_usernames)));
			}
		}
		// For some reason, none of them were deleted
		else
		{
			$this->session->set_flashdata('notice', lang('uploking_admin_user_manager_delete_error_label'));
		}
	
		redirect('admin/user_manager');
	}
	
	public function action()
	{
		switch ($this->input->post('btnAction'))
		{			
			case 'delete':
				$this->delete();
				break;
			default:
				redirect('admin/user_manager');
			break;
		}
	}
}
